 import UIKit
 import Alamofire
 import SwiftyJSON
 import TabPageViewController
 
 class HomeViewController: BaseController {
    var codeArray0: [ViolationCodeModel] = Array<ViolationCodeModel>()
    var codeArray1: [ViolationCodeModel] = Array<ViolationCodeModel>()
    var codeArray2: [ViolationCodeModel] = Array<ViolationCodeModel>()
    var codeArray3: [ViolationCodeModel] = Array<ViolationCodeModel>()
    var codeArray6: [ViolationCodeModel] = Array<ViolationCodeModel>()
    var codeArray12: [ViolationCodeModel] = Array<ViolationCodeModel>()
    lazy var tableView: UITableView = {
        let table = UITableView.init(frame: CGRect.init(x: 0, y: kStatusBarH, width: kScreenW, height: kScreenH - kStatusBarH - kTabBarH), style: .grouped)
        table.isScrollEnabled = false
        table.backgroundColor = tableBgColor
        return table
    }()
    // 应用数组
    lazy var AppArray : JSON = {
        let jsonStr =  "[{\"name\": \"违章办理\", \"url\": \"weizhang_icon\"},{\"name\": \"审车办理\", \"url\": \"shenche\"},{\"name\": \"驾证审核\", \"url\": \"jiazhenshenhe\"},{\"name\": \"行驶证补办\", \"url\": \"driving_change\"},{\"name\": \"驾证补换\", \"url\": \"driver_change\"},{\"name\": \"保险办理\", \"url\": \"baoxian\"},{\"name\": \"代缴罚款单\", \"url\": \"fine\"},{\"name\": \"抵押贷款\", \"url\": \"diyadaikuan\"},{\"name\": \"新车代购\", \"url\": \"buy_new_car\"},{\"name\": \"二手车买卖\", \"url\": \"trade_car\"},{\"name\": \"违章代码\", \"url\": \"daima_icon\"},{\"name\": \"今日油价\", \"url\": \"youjia_icon\"}]"
        let jsonData = jsonStr.data(using: String.Encoding.utf8, allowLossyConversion: false)
        return JSON(data: jsonData!)
    }()
    
    var flag = 0
    var imageView = ImageScrollView()
    var appView = AppListView()
    var carView = CarListView()
    var imageArray = Array<ImageScrollModel>()
    var applArray = Array<AppModel>()
    var carArray = Array<CarModel>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib
        self.view.addSubview(tableView)
        imageView = ImageScrollView.init(frame: .init(x: 0, y: 0, width: kScreenW, height: 150))
        tableView.addSubview(imageView)
        
        appView = AppListView.init(frame: .init(x: 0, y: 150, width: kScreenW, height: kScreenH - kTabBarH - kStatusBarH - 250))
        tableView.addSubview(appView)
        
        carView = CarListView.init(frame: .init(x: 20, y: kScreenH - kTabBarH - kStatusBarH - 100, width: kScreenW - 20, height: 100))
        tableView.addSubview(carView)
        
        let btnView = UIView.init(frame: CGRect(x: 0, y: kScreenH - kTabBarH - kStatusBarH - 100, width: 20, height: 100))
        let btn = UIButton.init(frame: CGRect(x: 0, y: 5, width: 20, height: 90))
        btn.setBackgroundImage(UIImage(named : "add_index"), for: .normal)
        btn.addTarget(self, action: #selector(self.addCarClick(sender:)), for: UIControlEvents.touchUpInside)
        btnView.addSubview(btn)
        tableView.addSubview(btnView)
        if reachability.isReachable {
            setupApp()
            loadViolationCodeList()//查询违章代码
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if reachability.isReachable {
            setupCycleImage()
            loadCarList()
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
        self.flag = 0
    }
    
    // 加载应用信息
    private func setupApp() {
        for (_,subJson) : (String,JSON) in AppArray {
            let model = AppModel.init(dic: subJson)
            self.applArray.append(model)
        }
        if self.applArray.count > 0 { //如果存在
            self.appView.setAppImage(applArray: self.applArray)
        }
    }
}
extension HomeViewController{

    // 加载轮播图片
    func setupCycleImage() {
        self.imageArray.removeAll()
        let urlString = "\(projectUrl)/source/list/sf001/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
        Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                if json["success"] == true {
                    for (_,subJson) : (String,JSON) in json["rdata"] {
                        let model = ImageScrollModel.init(dic: subJson)
                        self.imageArray.append(model)
                    }
                    if self.imageArray.count > 0 {
                        self.imageView.setScrollImage(imageArray: self.imageArray)
                    }
                }
                else{
                    print("获取轮播素材出错啦!\(json["rdata"])")
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }
            else{
                print("获取轮播素材出错：\(response.result.error!)") //输出错误日志
            }
        }
    }
    
    //加载车辆列表
    func loadCarList() {
        self.carArray.removeAll()
        let urlString = "\(projectUrl)/car/carList/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
        Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                if json["success"] == true {
                    for (_,subJson) : (String,JSON) in json["rdata"] {
                        let model = CarModel.init(dic: subJson)
                        self.carArray.append(model)
                    }
                    if self.carArray.count > 0 { //如果存在
                        self.carView.setCarList(carArray: self.carArray)
                    }
                }else{
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }
            else{
                print("车辆列表加载出错：\(response.result.error!)") //输出错误日志
            }
        }
    }
    
    // 添加车辆按钮事件
    func addCarClick(sender: UIButton){
        //判断是普通用户还是员工 2:员工
        if("2" == isEmployee){
            self.toAdd()
        }else{
            if reachability.isReachable {
                //先查看用户信息是否认证
                let urlString = "\(projectUrl)/user/auth/detail/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
                Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
                    if response.result.isSuccess{
                        let json = JSON(response.result.value as! [String : AnyObject])
                        if json["success"] == true {
                            if(json["rdata"]["authStatus"].exists()){
                                let authStatus = json["rdata"]["authStatus"].rawString()
                                if authStatus == "1" {//已经认证成功
                                    self.toAdd()
                                }else{
                                    self.toAuth()
                                }
                            }else{
                                self.toAuth()
                            }
                        }else{
                            self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                        }
                    }
                    else{
                        print(response.result.error!) //输出错误日志
                    }
                }
            }else{
                let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
                alertController.addAction(cancelAction)
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }
    //去添加车辆
    func toAdd(){
        if self.carArray.count >= 6 {
            let alertController = UIAlertController(title: alertTitle, message: "一个帐号最多添加6辆车！", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }else{
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(AddCarController(), animated: true)
            self.hidesBottomBarWhenPushed = false
        }
    }
    //弹出提示去跳转页面
    func toAuth(){
        let alertController = UIAlertController(title: alertTitle, message: "您的信息还未实名认证！", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "去认证", style: .default, handler:{
            (UIAlertAction) -> Void in
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(AuthViewController(), animated: true)
            self.hidesBottomBarWhenPushed = false
        })
        alertController.addAction(okAction)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
    // 编辑车辆信息按钮事件
    func editCarClick(sender: UIButton){
        let cic = CarInfoController()
        let car: CarModel = self.carArray[sender.tag]
        cic.car = car
        if flag == 0 {
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(cic, animated: true)
            self.hidesBottomBarWhenPushed = false
            self.flag = 1
        }
    }
    
    //应用点击事件
    func appClick(sender: UIButton){
        self.hidesBottomBarWhenPushed = true
        switch sender.tag {
        case 0:
            self.navigationController?.pushViewController(HandleViolationController(), animated: true)
        case 1:
            self.navigationController?.pushViewController(CarAuditController(), animated: true)
        case 2:
            self.navigationController?.pushViewController(DriverAuditController(), animated: true)
        case 3:
            self.navigationController?.pushViewController(DrivingLicenseController(), animated: true)
        case 4:
            self.navigationController?.pushViewController(DriveLicenseController(), animated: true)
        case 5:
            self.navigationController?.pushViewController(InsuranceController(), animated: true)
        case 6:
            self.navigationController?.pushViewController(CarFineController(), animated: true)
        case 7:
            let mc = MortgageController()
            mc.appTitle = "抵押贷款"
            mc.opType = 1
            self.navigationController?.pushViewController(mc, animated: true)
        case 8:
            self.navigationController?.pushViewController(PurchaseCarController(), animated: true)
        case 9:
            let mc = MortgageController()
            mc.appTitle = "二手车买卖"
            mc.opType = 2
            self.navigationController?.pushViewController(mc, animated: true)
        case 10:
            let controller1 = ViolationCodeViewController()
            controller1.codeArray = self.codeArray0
            let controller2 = ViolationCodeViewController()
            controller2.codeArray = self.codeArray1
            let controller3 = ViolationCodeViewController()
            controller3.codeArray = self.codeArray2
            let controller4 = ViolationCodeViewController()
            controller4.codeArray = self.codeArray3
            let controller5 = ViolationCodeViewController()
            controller5.codeArray = self.codeArray6
            let controller6 = ViolationCodeViewController()
            controller6.codeArray = self.codeArray12
            let tc = TabPageViewController.create()
            tc.isbackBtn = true
            tc.tabItems = [(controller1,"0分"),(controller2,"1分"),(controller3,"2分"),(controller4,"3分"),(controller5,"6分"),(controller6,"12分")]
            var option = TabPageOption()
            option.tabHeight = CGFloat(40)
            option.tabWidth = kScreenW / 6
            option.currentColor = appMainColor
            tc.option = option
            tc.title = "违章代码"
            self.navigationController?.pushViewController(tc, animated: true)
        case 11:
            self.navigationController?.pushViewController(OilPriceViewController(), animated: true)
        default:
            print("where are you going ？")
        }
        self.hidesBottomBarWhenPushed = false
    }
    //查询违章代码
    func loadViolationCodeList() {
        let urlString = "\(projectUrl)/car/vioCode/list/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
        Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                if json["success"] == true {
                    for (_,subJson) : (String,JSON) in json["rdata"]["0"] {
                        let model = ViolationCodeModel.init(dic: subJson)
                        self.codeArray0.append(model)
                    }
                    for (_,subJson) : (String,JSON) in json["rdata"]["1"] {
                        let model = ViolationCodeModel.init(dic: subJson)
                        self.codeArray1.append(model)
                    }
                    for (_,subJson) : (String,JSON) in json["rdata"]["2"] {
                        let model = ViolationCodeModel.init(dic: subJson)
                        self.codeArray2.append(model)
                    }
                    for (_,subJson) : (String,JSON) in json["rdata"]["3"] {
                        let model = ViolationCodeModel.init(dic: subJson)
                        self.codeArray3.append(model)
                    }
                    for (_,subJson) : (String,JSON) in json["rdata"]["6"] {
                        let model = ViolationCodeModel.init(dic: subJson)
                        self.codeArray6.append(model)
                    }
                    for (_,subJson) : (String,JSON) in json["rdata"]["12"] {
                        let model = ViolationCodeModel.init(dic: subJson)
                        self.codeArray12.append(model)
                    }
                }
                else{
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }
            else{
                print(response.result.error!) //输出错误日志
            }
        }
    }
 }
